import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:xianyu_school/utils/url.dart';
import 'package:xianyu_school/xianyuApp/entity/conversation/conversation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:xianyu_school/xianyuApp/message/messageDetailPage.dart';
import 'package:xianyu_school/xianyuApp/mine/Widgets/BallPulseIndicator.dart';

class FSMessagePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FSMessagePageState();
  }
}

class _FSMessagePageState extends State<FSMessagePage>{

  GlobalKey<EasyRefreshState> _easyRefreshKey = GlobalKey<EasyRefreshState>();
  GlobalKey<RefreshHeaderState> _headerKey = GlobalKey<RefreshHeaderState>();
  GlobalKey<RefreshFooterState> _footerKey = GlobalKey<RefreshFooterState>();
  var url = urls().url;
  String from;
  List<conversation> cs = [];
  var _futureBuilderFuture;
  WebSocketChannel channel;

  @override
  void initState() {
    _futureBuilderFuture = getchatlis();
    super.initState();
  }

//  void connetc() async {
//    SharedPreferences pres = await SharedPreferences.getInstance();
//    from = pres.getString("username");
//    channel = IOWebSocketChannel.connect("ws://192.168.1.105:8080/websocket/" + from);
//    channel.stream.listen((message){
//    });
//  }

  Future<void> getchatlis() async{
    SharedPreferences pref = await SharedPreferences.getInstance();
    from = pref.getString("username");
    Response re = await Dio().get(url+"/users/chatlist",queryParameters: {"user":from});
    if(re.data.toString()=="No more data") return re;
    var responseJson = json.decode(re.data.toString());
    responseJson.forEach((data) {
      setState(() {
        cs.add(conversation.fromJson(data));
      });
    });
    return re;
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CupertinoNavigationBar(
        backgroundColor: Colors.yellow,
        middle: Text("消息"),
      ),
      body: FutureBuilder(
        future: _futureBuilderFuture,
        builder: (context,snapshot){
          if(snapshot.hasData) return buildBody();
          else return BallPulseIndicator(
              color: Colors.black
          );
        },
      ),
    );
  }

  Widget buildBody() {
    return EasyRefresh(
      key: _easyRefreshKey,
      behavior: ScrollOverBehavior(),
      refreshHeader: ClassicsHeader(
        key: _headerKey,
        refreshText: "pullToRefresh",
        refreshReadyText: "releaseToRefresh",
        refreshingText: "refreshing...",
        refreshedText: "refreshed",
        moreInfo: "updateAt",
        bgColor: Colors.yellow,
        textColor: Colors.black87,
        moreInfoColor: Colors.black54,
        showMore: true,
      ),
      refreshFooter: ClassicsFooter(
        key: _footerKey,
        loadText: "pushToLoad",
        loadReadyText: "releaseToLoad",
        loadingText: "loading",
        loadedText: "loaded",
        noMoreText: "noMore",
        moreInfo: "updateAt",
        bgColor: Colors.transparent,
        textColor: Colors.black87,
        moreInfoColor: Colors.black54,
        showMore: false,
      ),
      autoLoad: false,
      child: buildList(),
      onRefresh: refreshFirstData,
      loadMore: refreshMoreData,
    );
  }

  Widget tou(int index){
    if (cs[index].user1!=from){
      return Image.memory(
        base64.decode(cs[index].user1img),
        fit: BoxFit.fill,
        gaplessPlayback:true,
      );
    }
    else{
      return Image.memory(
        base64.decode(cs[index].user2img),
        fit: BoxFit.fill,
        gaplessPlayback:true,
      );
    }
  }

  Widget text(int index){
    if (cs[index].user1!=from){
      return Text(
        cs[index].user1,
        style: TextStyle(
            color: Colors.black,
            fontSize: 16
        ),
      );
    }
    else{
      return Text(
        cs[index].user2,
        style: TextStyle(
            color: Colors.black,
            fontSize: 16
        ),
      );
    }
  }
  
  Widget MessageListItem(int index){
    return Row(
      children: [
        Container(
          margin: EdgeInsets.all(6),
          width: 45,
          height: 45,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
          ),
          child: tou(index)
        ),
        Expanded(
            child: Padding(
              padding: EdgeInsets.fromLTRB(10, 10, 18, 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  text(index),
                  Text(
                    cs[index].lastmessage,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14
                    ),
                  ),

                  SizedBox(
                    height: 10,
                  ),
                ],
              ),
            )
        ),
      ],
    );
  }

  Widget buildList() {
    return CustomScrollView(
      slivers: [
//        SliverToBoxAdapter(
//          child: Container(
//            child: FSMessageHeader(),
//          ),
//        ),

        SliverToBoxAdapter(
          child: SizedBox(
            height: 10,
          ),
        ),

        SliverList(
          delegate: SliverChildBuilderDelegate(
            (BuildContext buildContext, int index) {
              return GestureDetector(
                behavior: HitTestBehavior.opaque,
                child: MessageListItem(index),
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (_) {
                    if(cs[index].user1!=from) return messageDetailPage(to:cs[index].user1 ,);
                    else return messageDetailPage(to:cs[index].user2 ,);
                  }));
                },
              );
            },
            childCount:cs.length,
          ),
        )
      ],
    );
  }

  Future refreshFirstData() async {    
    await Future.delayed(Duration(seconds: 2), () {
      setState(() {
        
      });
    });
  }

  Future refreshMoreData() async {
    await Future.delayed(Duration(seconds: 2), () {
      setState(() {
        
      });
    });
  }
}